package com.eascs.partner.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.api.internal.StoreInfoService;
import com.eascs.admin.common.service.IO2oLoanapplyDubboService;
import com.eascs.admin.loanapplyoplog.LoanapplyOpLog;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.recordlog.constant.O2oLogType;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.brand.entity.O2oBrandEntity;
import com.eascs.brand.form.O2oBranPage;
import com.eascs.brand.service.O2oBrandService;
import com.eascs.brand.service.O2oPartnerService;
import com.eascs.common.util.StringUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.file.FileTypeConstants;
import com.eascs.partner.dao.JxsPartnerDao;
import com.eascs.partner.entity.DealerPartnerEntity;
import com.eascs.partner.service.JxsPartnerService;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.PaginationRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.AjaxConfirmButton;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.web.url.UrlHelper;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sequence.SequenceService;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.vo.ModelResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/jxsPartner/rest")
public class JxsPartnerRestController {
	private static Logger log = LoggerFactory.getLogger(JxsPartnerRestController.class);

	@Reference
	SysOrgService sysOrgService;
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;

	@Autowired
	private BaseUtils baseUtils;

	@Autowired
	private O2oBrandService brandService;

	@Autowired
	private JxsPartnerService jxsPartnerService;

	@Autowired
	private O2oPartnerService partnerService;
	@Autowired
	private JxsPartnerDao jxsPartnerDao;

	@Reference
	SequenceService sequenceService;
	@Autowired
	IO2oLoanapplyDubboService loanapplyDubboService;
	@Autowired
	private O2oLoanapplyService loanService;
	@Autowired
	private O2oLoanUserService o2oLoanUserService;
	@Autowired
	private StoreInfoService storeInfoService;

	@Value("${web.crm.url}")
	private String crmUrl;

	@RequestMapping("/view_add")
	public BaseRestResult<String> openAdd(String brandId, String batchClassification, String certNo, String isShare) {
		User user = UserHolder.getUser();
		ViewContext.put("currentUser", user.getCname());
		ViewContext.put("currentUserCode", user.getNo());
		ViewContext.put("brandId", brandId);
		ViewContext.put("batchClassification", batchClassification);
		ViewContext.put("isShare", isShare);

		//if (StringUtils.equalsIgnoreCase(batchClassification, "无贷款户")) {
			List<ActOrgEntity> orgProvince = sysOrgService.getOrgProvince();
			ViewContext.put("ActOrgEntitys", orgProvince);
			ViewContext.put("crmUrl", crmUrl);
			return HtmlRestResult.popHtmlFragment("/partner/jxsPartner_add");
		/*} else {
			PageResult<Object[]> pageResult = new PageResult<Object[]>();
			String titles[] = { "贷款人编号", "借款人姓名", "信贷经理", "经营平台", "省区", "放款日期" };
			PaginationInfo pagingInfo = new PaginationInfo(pageResult, titles, null);
			pagingInfo.setBuildSelectBox(true);
			ViewContext.put("paginationInfo", pagingInfo);
			return HtmlRestResult.popHtmlFragment("/partner/jxsPartner_add_with_loan");
		}*/
	}

	@RequestMapping("/search_loan")
	public PaginationRestResult searchLoan(String brandId, String batchClassification, String searCertNo) {
		PageResult<Object[]> pageResult = new PageResult<Object[]>();
		String titles[] = { "贷款人编号", "借款人姓名", "信贷经理", "经营平台", "省区", "放款日期" };
		if (StringUtils.isNotBlank(StringUtils.trimToEmpty(searCertNo))) {
			pageResult = loanapplyDubboService.getLoanapplyInfoByIdCard(searCertNo);
		}
		PaginationInfo pagingInfo = new PaginationInfo(pageResult, titles, null);
		pagingInfo.setBuildSelectBox(true);
		pagingInfo.setRendTo("#loanpagination");
		return PaginationRestResult.buildPaginationRestResult(pagingInfo);
	}

	@RequestMapping("/view_detail")
	public BaseRestResult<String> detailModel(String partnerId) {
		String agreeUrl = baseUtils.getApprovalAgreeUrl(partnerId, "", ProcessTemplate.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("parameter", partnerId);
		DealerPartnerEntity dealerPartnerEntity = jxsPartnerDao.queryJxsPartnerEntityById(partnerId);
		ViewContext.put("vo", dealerPartnerEntity);
		ViewContext.put("currentUser", dealerPartnerEntity.getOperator());
		ViewContext.put("currentUserCode", dealerPartnerEntity.getOperatorId());
		ViewContext.put("batchClassification", dealerPartnerEntity.getBatchClassification());

		//if (StringUtils.isBlank(dealerPartnerEntity.getLoanId())) {
			List<ActOrgEntity> orgProvince = sysOrgService.getOrgProvince();
			ViewContext.put("ActOrgEntitys", orgProvince);
			ViewContext.put("crmUrl", crmUrl);
			return HtmlRestResult.popHtmlFragment("/partner/jxsPartner_add");
		/*} else {
			// 有贷款户的经销商
			String loanapplyNo = dealerPartnerEntity.getLoanId();
			ViewContext.put("loanapplyNo", loanapplyNo);
			O2oLoanapplyEntity loanapply = loanService.findById(loanapplyNo);
			if (loanapply != null && loanapply.getLoanId() != null) {
				ViewContext.put("loanapply", loanapply);
				O2oLoanUserEntity loanUser = o2oLoanUserService.findById(loanapply.getLoanId(),
						loanapply.getLoanapplyNo());
				ViewContext.put("loanUser", loanUser);
			}
			return HtmlRestResult.popHtmlFragment("/partner/jxsPartner_view_with_loan");
		}*/
	}

	/**
	 * 脱敏查看弹窗
	 * 
	 * @param partnerId
	 * @return
	 */
	@RequestMapping("/show_window")
	public BaseRestResult<String> showWindow(String partnerId) {
		DealerPartnerEntity dealerPartnerEntity = jxsPartnerDao.queryJxsPartnerEntityById(partnerId);
		ViewContext.put("vo", dealerPartnerEntity);
		ViewContext.put("crmUrl", crmUrl);
		return HtmlRestResult.popHtmlFragment("/partner/jxsPartner_show");
	}

	/**
	 * 局部加载上传附件
	 * 
	 * @param parameter
	 * @return
	 */
	@RequestMapping("/loadfile")
	public HtmlRestResult querySQBZJFile(String parameter, String wfStatus) {
		if (wfStatus.equals("-1") || wfStatus.equals("3")) {
			queryDataList(parameter, FileTypeConstants.JXS_PARTNER_TYPE_RPMENT, null);
			queryDataListPicture(parameter, FileTypeConstants.JXS_PARTNER_TYPE_PICTURE, null);
			queryDataListEvidence(parameter, FileTypeConstants.JXS_PARTNER_TYPE_EVIDENCE, null);
			ViewContext.put("operation", "update");
		} else {
			queryDataList(parameter, FileTypeConstants.JXS_PARTNER_TYPE_RPMENT, "detail");
			queryDataListPicture(parameter, FileTypeConstants.JXS_PARTNER_TYPE_PICTURE, "detail");
			queryDataListEvidence(parameter, FileTypeConstants.JXS_PARTNER_TYPE_EVIDENCE, "detail");
			ViewContext.put("operation", "disabled");
		}
		ViewContext.put("parameter", parameter);
		return HtmlRestResult.html("/partner/parterfile");
	}

	public void queryDataList(String loanapplyNo, String code, String detailFlag) {
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(loanapplyNo, "'" + code + "'");
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[] { null,
				ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		if (!"detail".equals(detailFlag)) {
			AjaxConfirmButton[] dealButton = null;
			dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
			paginationInfo.setMoreButtons(dealButton);
		}
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildRowNumber(true);
		ViewContext.put("pageResult", paginationInfo);// 个人附件
	}

	public void queryDataListPicture(String loanapplyNo, String code, String detailFlag) {
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(loanapplyNo, "'" + code + "'");
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[] { null,
				ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		if (!"detail".equals(detailFlag)) {
			AjaxConfirmButton[] dealButton = null;
			dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
			paginationInfo.setMoreButtons(dealButton);
		}
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildRowNumber(true);
		ViewContext.put("pageResultPicture", paginationInfo);// 个人附件
	}

	public void queryDataListEvidence(String loanapplyNo, String code, String detailFlag) {
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(loanapplyNo, "'" + code + "'");
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[] { null,
				ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		if (!"detail".equals(detailFlag)) {
			AjaxConfirmButton[] dealButton = null;
			dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
			paginationInfo.setMoreButtons(dealButton);
		}
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildRowNumber(true);
		ViewContext.put("pageResultEvidence", paginationInfo);// 个人附件
	}

	/**
	 * 贷款单经销商添加
	 * 
	 * @param param
	 * @return
	 */
	@RequestMapping("/add_with_loan")
	public BaseRestResult<String> addWithLoan(DealerPartnerEntity param, HttpServletRequest request) {
		String[] loanIds = request.getParameterValues("ids");
		if (loanIds == null || loanIds.length == 0) {
			return BaseRestResult.warn("请至少选择一个贷款单");
		}
		if (loanIds.length > 1) {
			return BaseRestResult.warn("最多只能选择一个贷款单");
		}
		// 贷款单ID
		String loanId = loanIds[0];
		param.setLoanId(loanId);
		String licenceName = storeInfoService.getLicenceNameByLoanapplyNo(loanId);
		if (StringUtils.isBlank(licenceName)) {
			return BaseRestResult.warn("贷款单关联的门店营业执照为空，请联系管理员");
		}
		param.setBusinessLicenseName(licenceName);

		String provinceCode = jxsPartnerDao.getProvinceByLoan(loanId);
		if (StringUtils.isBlank(provinceCode)) {
			return BaseRestResult.warn("获取贷款单省区失败");
		}
		ActOrgEntity provinceOrg = null;
		List<ActOrgEntity> provinces = sysOrgService.getOrgProvince();
		for (ActOrgEntity org : provinces) {
			if (StringUtils.equalsIgnoreCase(org.getUnitCode(), provinceCode)) {
				provinceOrg = org;
				break;
			}
		}
		if (provinceOrg == null) {
			return BaseRestResult.warn("获取贷款单省区失败");
		}
		param.setOrgProvinceId(provinceOrg.getOrgId());
		param.setOrgProvince(provinceOrg.getOrgName());
		List<ActOrgEntity> actOrgList = sysOrgService.getLeafNodeByParentId(provinceOrg.getOrgId());
		if (actOrgList == null || actOrgList.size() == 0) {
			return BaseRestResult.warn("找不到经办平台，请联系管理员");
		}
		ActOrgEntity actOrgEntity = null;
		for (ActOrgEntity org : actOrgList) {
			if (org.getOrgLevel() == 4) {
				actOrgEntity = org;
				break;
			}
		}
		if (actOrgEntity == null) {
			return BaseRestResult.warn("找不到经办平台对应的省区金融部，请联系管理员");
		}
		User user = UserHolder.getUser();
		param.setOrgId(actOrgEntity.getUnitNo());
		param.setOrgName(actOrgEntity.getOrgName());
		param.setCreator(user.getCname());
		param.setCreateDate(new Date());
		param.setStatus(JxsPartnerDao.status_normal);
		param.setWfStatus(JxsPartnerDao.wfstatus_new);
		String patternCode = sequenceService.getSeq("O2O_JXS_PARTNER_NO", 5, "JXS_HZF");
		param.setPatternCode(patternCode);
		int insertResult = jxsPartnerDao.insert(param);
		if (insertResult == 0) {
			return BaseRestResult.warn("新增失败");
		}
		LoanapplyOpLog log = getEntity(UserHolder.getUser().getCname(), O2oLogType.PARTNER_UPDATE_APT,
				param.getBrandId(), "新增品牌经销商合作方信息");
		partnerService.saveEntityLog(log);
		ViewContext.put("vo", param);
		return BaseRestResult.info("添加成功").andRedirect("/brand/detail?parameter=" + param.getBrandId());
	}

	@RequestMapping("/add")
	public BaseRestResult<String> add(DealerPartnerEntity param) {
		String[] arr = param.getOrgProvinceId().split("_");
		param.setOrgProvinceId(arr[0]);
		param.setOrgProvince(arr[1]);
		List<ActOrgEntity> actOrgList = sysOrgService.getLeafNodeByParentId(param.getOrgProvinceId());
		if (actOrgList == null || actOrgList.size() == 0) {
			return BaseRestResult.warn("找不到经办平台，请联系管理员");
		}
		ActOrgEntity actOrgEntity = null;
		for (ActOrgEntity org : actOrgList) {
			if (org.getOrgLevel() == 4)
				actOrgEntity = org;
		}
		if (actOrgEntity == null) {
			return BaseRestResult.warn("找不到经办平台对应的省区金融部，请联系管理员");
		}
		param.setOrgProvince(param.getOrgProvince());
		param.setOrgId(actOrgEntity.getUnitNo());
		param.setOrgName(actOrgEntity.getOrgName());

		DealerPartnerEntity result = null;
		if (StringUtils.isNotBlank(param.getId())) {
			result = jxsPartnerDao.queryJxsPartnerEntityById(param.getId());
		}
		// else if(result == null &&
		// StringUtils.isNotBlank(param.getCorporationName())){
		// result =
		// jxsPartnerDao.queryJxsPartnerEntityByName(param.getCorporationName());
		// }
		User user = UserHolder.getUser();
		param.setUpdator(user.getCname());
		param.setUpdateDate(new Date());
		LoanapplyOpLog log;
		if (result != null) {
			param.setPatternCode(result.getPatternCode());
			param.setBrandId(result.getBrandId());
			param.setStatus(result.getStatus());
			param.setWfStatus(result.getWfStatus());
			param.setCreateDate(result.getCreateDate());
			param.setCreator(result.getCreator());
			int insertResult = jxsPartnerDao.updateById(param);
			if (insertResult == 0) {
				return BaseRestResult.warn("修改失败");
			}
			log = getEntity(UserHolder.getUser().getCname(), O2oLogType.PARTNER_UPDATE_APT, param.getBrandId(),
					"修改品牌经销商合作方信息");

			partnerService.saveEntityLog(log);
			ViewContext.put("crmUrl", crmUrl);
			ViewContext.put("vo", param);
			return BaseRestResult.info("修改成功").andRedirect(UrlHelper.build("/jxsPartner/index"));
		} else {
			param.setCreator(user.getCname());
			param.setCreateDate(new Date());
			param.setStatus(JxsPartnerDao.status_normal);
			param.setWfStatus(JxsPartnerDao.wfstatus_new);
			String patternCode = sequenceService.getSeq("O2O_JXS_PARTNER_NO", 5, "JXS_HZF");
			param.setPatternCode(patternCode);
			int insertResult = jxsPartnerDao.insert(param);
			if (insertResult == 0) {
				return BaseRestResult.warn("新增失败");
			}
			log = getEntity(UserHolder.getUser().getCname(), O2oLogType.PARTNER_UPDATE_APT, param.getBrandId(),
					"新增品牌经销商合作方信息");

			partnerService.saveEntityLog(log);
			ViewContext.put("crmUrl", crmUrl);
			ViewContext.put("vo", param);
			return BaseRestResult.info("添加成功,请上传附件").andRedirect("/brand/detail?parameter=" + param.getBrandId() + "&p="+param.getId());
		}
	}

	@RequestMapping("/view_edit")
	public BaseRestResult<String> openEdit(String partnerId) {
		String agreeUrl = baseUtils.getApprovalAgreeUrl(partnerId, "", ProcessTemplate.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("parameter", partnerId);

		DealerPartnerEntity dealerPartnerEntity = jxsPartnerDao.queryJxsPartnerEntityById(partnerId);
		List<ActOrgEntity> orgProvince = sysOrgService.getOrgProvince();
		ViewContext.put("ActOrgEntitys", orgProvince);
		ViewContext.put("vo", dealerPartnerEntity);
		ViewContext.put("crmUrl", crmUrl);

		ViewContext.put("currentUser", dealerPartnerEntity.getOperator());
		ViewContext.put("currentUserCode", dealerPartnerEntity.getOperatorId());
		ViewContext.put("batchClassification", dealerPartnerEntity.getBatchClassification());

		O2oBrandEntity brand = brandService.queryBrandEntityById(dealerPartnerEntity.getBrandId()).getModel();
		ViewContext.put("brand", brand);
		return HtmlRestResult.popHtmlFragment("/partner/jxsPartner_edit");
	}

	@RequestMapping("/delete")
	public BaseRestResult<String> delete(String partnerId) {
		if (StringUtil.isEmpty(partnerId)) {
			return BaseRestResult.warn("参数为空，无法删除！");
		} else {
			Boolean deleteResult = jxsPartnerDao.deleteJxsPartnerEntityById(partnerId);
			if (deleteResult) {
				return BaseRestResult.info("删除成功").andRefresh();
			} else {
				return BaseRestResult.info("删除失败");
			}
		}
	}

	@RequestMapping("/list")
	public PaginationRestResult getPartnerByPage(O2oBranPage branPage) {
		String pageUrl = "/rpartner/detail";
		String brandId = branPage.getBrandId() == null ? "" : branPage.getBrandId();
		pageUrl = UrlUtil.appendUrl(pageUrl, "brandId", brandId);
		pageUrl = pageUrl + "&pageIndex=";
		branPage.setPageSize(10);
		PageResult<Object[]> pageResult = jxsPartnerDao.queryPartnerEntityByPage(branPage);
		String titles[] = { "申报单号", "一批商渠道名称", "创建时间", "经办人", "一批商分类", "融资额度（万元）", "状态" };

		SelectDataOption[] selectDataOptions = { null, null, null, null, null, null,
				new SelectDataOption("parWFStutus") };

		Button edit = ButtonHelper.createAjaxButton(null, "/jxsPartner/rest/view_edit?partnerId=", "editPartner");// parameter为合作方id
		Button[] Button = new Button[] { edit, null };

		/*Button delete = ButtonHelper.createAjaxConfirmButton("删除", "/jxsPartner/rest/delete?partnerId=", "editPartner");
		delete.setShowButtonFilter(new ShowButtonFilter() {
			@Override
			public boolean filter(Object param) {
				Object[] params = (Object[]) param;
				if ("-1".equals(params[7] + "") || "3".equals(params[7] + ""))
					return true;
				else
					return false;
			}
		});
		Button startFlow = ButtonHelper.createAjaxButton("发起流程", "/jxsPartner/rest/jxsStartFlow?id=",
				"startPartnerFlow");// parameter为合作方id
		startFlow.setShowButtonFilter(new ShowButtonFilter() {
			@Override
			public boolean filter(Object param) {
				Object[] params = (Object[]) param;
				if ("-1".equals(params[7] + "") || "3".equals(params[7] + ""))
					return true;
				else
					return false;
			}
		});
		Button edit = ButtonHelper.createAjaxButton("编辑", "/jxsPartner/rest/view_edit?partnerId=", "editPartner");// parameter为合作方id
		edit.setShowButtonFilter(new ShowButtonFilter() {
			@Override
			public boolean filter(Object param) {
				Object[] params = (Object[]) param;
				if (StringUtils.isBlank((String) params[8])) {
					if ("-1".equals(params[7] + "") || "3".equals(params[7] + "")) {
						return true;
					}
				}
				return false;
			}
		});

		Button[] titleButtons = new Button[] { edit, delete, startFlow };*/
		PaginationInfo o2oPagingInfo = new PaginationInfo(pageResult, titles, pageUrl);
		o2oPagingInfo.setSelectDataOptions(selectDataOptions);
		o2oPagingInfo.setBuildPagingNavigation(true);
		o2oPagingInfo.setFirstRenderColumnIndex(1);
		o2oPagingInfo.setTitleButtons(Button);
		//o2oPagingInfo.setMoreButtons(titleButtons);
		o2oPagingInfo.setRendTo("#partner_detail");
		ViewContext.put("branPage", branPage);
		return PaginationRestResult.buildPaginationRestResult(o2oPagingInfo);
	}

	/**
	 * 
	 * @Title: jxsStartFlow
	 * @Description: 经销商合作方流程启动（/jxsPartner/rest/jxsStartFlow）
	 * @author user
	 * @param id
	 * @return
	 * @return BaseRestResult<String>
	 * @throws @date
	 *             2017年9月13日 下午6:20:58
	 */
	@RequestMapping("/jxsStartFlow")
	public BaseRestResult<String> jxsStartFlow(String id) {
		DealerPartnerEntity dealerPartnerEntity = jxsPartnerService.getEntityById(id);
		ModelResult<Boolean> checkRole = isJxsCurrentRole(dealerPartnerEntity, "jxsStartFlow");
		if (!checkRole.getModel()) {
			return BaseRestResult.warn(checkRole.getErrMsg());
		}
		if (StringUtils.isBlank(dealerPartnerEntity.getLoanId())) {
			ModelResult<Boolean> checkAttachment = partnerService.checkJxsAttachment(id);
			if (!checkAttachment.isSuccess() || !checkAttachment.getModel()) {
				return BaseRestResult.warn(checkAttachment.getErrMsg());
			}
		}
		ModelResult<Boolean> startUp = jxsPartnerService.startUp(id);
		if (startUp.isSuccess() && startUp.getModel()) {
			return BaseRestResult.info("流程启动成功").andRedirect(UrlHelper.build("/jxsPartner/index"));
		} else {
			return BaseRestResult.warn(startUp.getErrMsg());
		}
	}

	public ModelResult<Boolean> isJxsCurrentRole(DealerPartnerEntity entity, String operateType) {
		ModelResult<Boolean> modelResult = new ModelResult<>();
		User user = UserHolder.getUser();
		if (!user.getNo().equals(entity.getOperatorId()) && !user.isSuperAdministrator()) {
			if ("edit".equals(operateType)) {
				modelResult.setErrMsg("该信息只能由经办人编辑");
			} else if ("delete".equals(operateType)) {
				modelResult.setErrMsg("该信息只能由经办人删除");
			} else if ("jxsStartFlow".equals(operateType)) {
				modelResult.setErrMsg("该流程只能由经办人发起");
			}
			modelResult.setModel(false);
			return modelResult;
		}
		modelResult.setModel(true);
		return modelResult;
	}

	/**
	 * 
	 * @Title: jxsStartFlow
	 * @Description: 经销商合作方流程详情
	 * @author user
	 * @return
	 * @return BaseRestResult<String>
	 * @throws @date
	 *             2017年9月13日 下午6:20:58
	 */
	@RequestMapping("/view_flow")
	public BaseRestResult<String> viewFlow(String approvalStatus, String referId, String nodeAuditorId) {
		String approvalUrl = baseUtils.getApprovalUrl(nodeAuditorId,
				ProcessTemplate.PROECESS_TYPE_JXS_PARTNERS_AUDIT_BP);// 审批代办列表详情URL
		DealerPartnerEntity dealerPartnerEntity = jxsPartnerService.getEntityById(referId);
		String agreeUrl = baseUtils.getApprovalAgreeUrl(referId, nodeAuditorId, ProcessTemplate.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("approvalUrl", approvalUrl);
		ViewContext.put("currentUser", dealerPartnerEntity.getOperator());
		ViewContext.put("approvalStatus", approvalStatus);// 流程经办状态是待办/已办/已发起，待办状态才显示审批栏
		ViewContext.put("vo", dealerPartnerEntity);
		ViewContext.put("parameter", referId);
		ViewContext.put("batchClassification", dealerPartnerEntity.getBatchClassification());
		// 有贷款户的经销商
		String loanapplyNo = dealerPartnerEntity.getLoanId();
		//if (StringUtils.isBlank(loanapplyNo)) {
			O2oBrandEntity brandEntity = brandService.getEntityById(dealerPartnerEntity.getBrandId());
			queryDataList(referId, FileTypeConstants.JXS_PARTNER_TYPE_RPMENT, "detail");
			List<ActOrgEntity> orgProvince = sysOrgService.getOrgProvince();
			ViewContext.put("ActOrgEntitys", orgProvince);
			ViewContext.put("brandEntity", brandEntity);
			return HtmlRestResult.popHtmlFragment("/partner/jxs_partner_flow");
		/*} else {
			O2oLoanapplyEntity loanapply = loanService.findById(loanapplyNo);
			if (loanapply != null && loanapply.getLoanId() != null) {
				ViewContext.put("loanapply", loanapply);
				O2oLoanUserEntity loanUser = o2oLoanUserService.findById(loanapply.getLoanId(),
						loanapply.getLoanapplyNo());
				ViewContext.put("loanUser", loanUser);
			}
			return HtmlRestResult.popHtmlFragment("/partner/jxsPartner_view_with_loan");
		}*/
	}

	public LoanapplyOpLog getEntity(String opPsn, String type, String up, String down) {
		LoanapplyOpLog log = new LoanapplyOpLog();
		log.setOpPsn(opPsn);
		log.setOpType(type);
		log.setOpTypeName(O2oLogType.getStringName(type));
		log.setOpDate(new Date());
		log.setOpContentUp(up);
		log.setOpContentDown(down);
		return log;
	}
}
